package com.songshuai.sales.tool.aop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.songshuai.webapi.baseapi.enumerations.ResultStatus;
import com.songshuai.webapi.baseapi.pojo.QueryRes;
import com.songshuai.webapi.common.httpclient.HttpClientUtil;
import com.songshuai.webapi.common.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Aspect
@Slf4j
@Component
public class SSOAspect{

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${pangu.tool.getCurrentUser}")
    private String getPanguUserInfo;


    @Pointcut(value = "execution(public * com.songshuai.sales.tool.controller.*.*(..))")
    public void rlAop(){

    }

    @Around("rlAop()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();

        String authorization = request.getHeader("Authorization");
        Map<String, Object> result = new ConcurrentHashMap<>();
        if (StringUtils.isNotBlank(authorization)) {
            String[] strings = authorization.split(" ");
            if (strings.length > 0) {
                String auth = strings[strings.length - 1];
                //前端传过来的token不为空
                if (StringUtils.isNotBlank(auth)) {
                    String userInfo = redisUtil.getString(auth);
                    //如果当前redis能获取当前用户信息  则认证通过
                    //如果当前redis不存在用户信息   则说明当前用户登录过期   去远程盘古系统拿用户信息   拿不到让用户退出登录
                    if (StringUtils.isNotBlank(userInfo)) {
                        refashtoke(auth,userInfo);
                        Object proceed = proceedingJoinPoint.proceed();
                        return proceed;
                    } else {
                        try {
                            Map<String,String> head=new HashMap<>();
                            head.put("Authorization",authorization);
                            head.put("accept","application/json");
                            String remoteUserInfo = HttpClientUtil.sendGetHttps(getPanguUserInfo,null,head);
                            log.info("调用盘古远程接口（根据token获取用户信息）"+"GET HTTPS &&&"+"url="+getPanguUserInfo+"&&&& header="+head.toString()+" &&&&返回结果"+remoteUserInfo);
                            if (StringUtils.isNotBlank(remoteUserInfo)) {
                                JSONObject jsonObject = JSON.parseObject(remoteUserInfo);
                                Integer status = jsonObject.getInteger("status");
                                if(null!=status){
                                    if(0==status){
                                        userInfo=jsonObject.getString("result");
                                        redisUtil.set(auth,userInfo,1800);
                                        refashtoke(auth,userInfo);
                                        Object proceed = proceedingJoinPoint.proceed();
                                        return proceed;
                                    }else{
                                        return new QueryRes(ResultStatus.PANGU_USERINFO_EEROR.getErrorCode(), "盘古系统远程接口异常,返回信息"+jsonObject.getString("info"));
                                    }

                                }else{
                                    return new QueryRes(ResultStatus.PANGU_USERINFO_EEROR.getErrorCode(), "盘古系统远程接口异常");
                                }
                            } else {
                                return new QueryRes(ResultStatus.PANGU_USERINFO_EEROR.getErrorCode(), "盘古系统远程接口返回null");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            return new QueryRes(ResultStatus.PANGU_USERINFO_EEROR.getErrorCode(), "盘古系统远程接口无响应");
                        }
                    }
                }
            } else {
                return new QueryRes(401, "token格式不正确");
            }

        } else {
            return new QueryRes(401, "请求此资源需要完全的身份验证");
        }
        Object proceed = proceedingJoinPoint.proceed();
        return proceed;
    }
    @Async
    public void refashtoke(String auth,String userInfo){
        request.setAttribute("loginUser",userInfo);
        redisUtil.expire(auth,1800);
    }
}
